import 'package:card_topia/api/api_path.dart';
import 'package:card_topia/api/network_util.dart';
import 'package:card_topia/common_model/user_info_model.dart';
import 'package:card_topia/utils/shared_preference_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

///用户信息

var userInfoProvider = ChangeNotifierProvider((ref) => UserInfoProvider());

class UserInfoProvider extends ChangeNotifier{
  UserInfoModel? userInfo;


  Future<bool> setUserInfo(Map data)async{
    userInfo = UserInfoModel.fromJson(data);
    NetworkUtil.setDioOption(refreshToken: userInfo?.refreshToken,token: userInfo?.token);
    notifyListeners();
    return SPUtil.saveMap(key: SPUtil.userInfoKey, value: userInfo!.toJson());
  }

  clearUserInfo(){
    userInfo = null;
    SPUtil.deleteData(key: SPUtil.userInfoKey);
    notifyListeners();
  }

  //加载缓存数据
  loadSP(){
    final result = SPUtil.getMap(key: SPUtil.userInfoKey);
    if(result!=null){
      userInfo = UserInfoModel.fromJson(result);
      NetworkUtil.setDioOption(refreshToken: userInfo?.refreshToken,token: userInfo?.token);
      notifyListeners();
    }
  }

  //获取用户信息
  Future<bool> getUserInfo()async{
    final result = await NetworkUtil.get(path: ApiPath.getUserInfoPath);
    if(result.success){
      userInfo = UserInfoModel.fromJson(result.data);
      SPUtil.saveMap(key: SPUtil.userInfoKey, value: userInfo!.toJson());
      notifyListeners();
    }
    return result.success;
  }
}